import * as vscode from 'vscode';

// LLM分析结果接口（后端返回）
interface LLMAnalysisResult {
  analysis: string;      // 错误分析文本
  suggestions: string;   // 多行修复代码（每行一个修复建议）
}

// 解析出的修复建议
interface ParsedFixSuggestion {
  suggestedCode: string;   // 建议的代码行
  lineIndex: number;       // 在suggestions中的行索引
}

// 匹配到的修复建议
interface MatchedFixSuggestion {
  originalCode: string;
  suggestedCode: string;
  line: number;
  originalIndentation: string;  // 原始缩进
  adjustedCode: string;         // 调整缩进后的代码
  lineIndex: number;            // 在suggestions中的行索引
}

// 代码匹配配置
const CODE_MATCHING_CONFIG = {
  maxDistanceFromError: 10,     // 最大距离错误行的行数
  minSimilarity: 0.6,          // 最小相似度阈值
  preserveIndentation: true,   // 保持缩进
  trimComparison: true         // 比较时去除首尾空白
};

/**
 * 代码修复建议管理器
 */
class CodeFixSuggestionManager {
  private fixDecorations = new Map<string, vscode.TextEditorDecorationType>();
  private activeFixes = new Map<string, MatchedFixSuggestion[]>();
  private currentPanel: vscode.WebviewPanel | null = null;

  private removeComments(code: string): string {
    let result = code;
    
    // 去除单行注释 // (JavaScript, TypeScript, C++, Java等)
    result = result.replace(/\/\/.*$/gm, '');
    
    // 去除单行注释 # (Python, Ruby, Shell等)
    result = result.replace(/#.*$/gm, '');
    
    // 去除多行注释 /* */ (JavaScript, TypeScript, C++, Java等)
    result = result.replace(/\/\*[\s\S]*?\*\//g, '');
    
    // 去除HTML/XML注释 <!-- -->
    result = result.replace(/<!--[\s\S]*?-->/g, '');
    
    // 去除SQL注释 --
    result = result.replace(/--.*$/gm, '');
    
    // 去除Python多行字符串注释 """ """ 或 ''' '''
    result = result.replace(/"""[\s\S]*?"""/g, '');
    result = result.replace(/'''[\s\S]*?'''/g, '');
    
    // 清理多余的空白字符
    return result.trim();
  }
  /**
   * 处理后端返回的LSP分析结果
   */
  async processLSPAnalysisResult(
    analysisResult: LLMAnalysisResult,
    diagnostic: vscode.Diagnostic,
    document: vscode.TextDocument
  ): Promise<void> {
    try {
      console.log('开始处理后端返回的LSP分析结果');
      console.log('Analysis:', analysisResult.analysis);
      console.log('Suggestions:', analysisResult.suggestions);
      
      // 从suggestions字段中解析修复代码
      const parsedSuggestions = this.parseSuggestionsText(analysisResult.suggestions);
      
      if (parsedSuggestions.length === 0) {
        console.log('无法从suggestions中解析出代码建议，显示纯文本分析结果');
        this.showAnalysisOnlyModal(analysisResult);
        return;
      }

      console.log(`从suggestions中解析出 ${parsedSuggestions.length} 个代码建议`);

      // 匹配修复建议到具体代码位置
      const matchedFixes = await this.matchFixSuggestions(
        parsedSuggestions, 
        diagnostic, 
        document
      );
      
      if (matchedFixes.length === 0) {
        console.log('代码匹配失败，无法定位修复位置');
        this.showFailedMatchModal(analysisResult);
        return;
      }

      console.log(`成功匹配 ${matchedFixes.length} 个修复建议`);

      // 显示修复建议 - 使用模态框而不是侧边面板
      await this.showFixSuggestionsModal(matchedFixes, diagnostic, document, analysisResult);
      
    } catch (error) {
      console.error('处理LSP分析结果失败:', error);
    }
  }

  // ... 保持原有的解析和匹配方法不变 ...
  private parseSuggestionsText(suggestions: string): ParsedFixSuggestion[] {
    const parsedSuggestions: ParsedFixSuggestion[] = [];
    
    try {
      const lines = suggestions.split('\n').map(line => line.trim()).filter(line => line.length > 0);
      console.log('解析suggestions文本:', lines);

      for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        if (this.isCodeLine(line)) {
          parsedSuggestions.push({
            suggestedCode: line,
            lineIndex: i
          });
          console.log(`✅ 解析到代码行 ${i + 1}: "${line}"`);
        } else {
          console.log(`❌ 跳过非代码行 ${i + 1}: "${line}"`);
        }
      }
    } catch (error) {
      console.error('解析suggestions文本失败:', error);
    }
    return parsedSuggestions;
  }

  private isCodeLine(line: string): boolean {
    const codePatterns = [
      /^[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*/,
      /^[a-zA-Z_][a-zA-Z0-9_]*\s*\(/,
      /^(def|class|if|for|while|try|with)\s+/,
      /^(let|const|var|function)\s+/,
      /^(int|string|bool|float|double)\s+/,
    ];
    
    const excludePatterns = [
      /^(修复建议|建议|提示|注意|错误|警告)/,
      /^(fix|suggestion|note|error|warning)/i,
      /^[^\w\s]/,
      /^\d+\./,
    ];
    
    for (const pattern of excludePatterns) {
      if (pattern.test(line)) return false;
    }
    
    for (const pattern of codePatterns) {
      if (pattern.test(line)) return true;
    }
    
    const hasCodeElements = /[=\(\)\[\]\{\}]/.test(line) && 
                           !/^[^a-zA-Z]*$/.test(line);
    return hasCodeElements;
  }

  private async matchFixSuggestions(
    parsedSuggestions: ParsedFixSuggestion[], 
    diagnostic: vscode.Diagnostic, 
    document: vscode.TextDocument
  ): Promise<MatchedFixSuggestion[]> {
    const matchedFixes: MatchedFixSuggestion[] = [];
    const errorLine = diagnostic.range.start.line;
    
    console.log(`开始匹配 ${parsedSuggestions.length} 个解析出的建议，错误行: ${errorLine + 1}`);

    for (const suggestion of parsedSuggestions) {
      try {
        const matchResult = await this.findBestMatchForSuggestion(
          suggestion, 
          document, 
          errorLine
        );

        if (matchResult) {
          matchedFixes.push(matchResult);
          console.log(`✅ 匹配成功: 行${matchResult.line + 1}`);
        } else {
          console.log(`❌ 匹配失败: "${suggestion.suggestedCode}"`);
        }
      } catch (error) {
        console.error(`匹配建议失败: ${suggestion.suggestedCode}`, error);
      }
    }

    return matchedFixes;
  }

  private async findBestMatchForSuggestion(
    suggestion: ParsedFixSuggestion,
    document: vscode.TextDocument,
    errorLine: number
  ): Promise<MatchedFixSuggestion | null> {
    const suggestedCode = suggestion.suggestedCode.trim();
    const identifierMatch = suggestedCode.match(/^(\w+)/);
    if (!identifierMatch) return null;
    
    const identifier = identifierMatch[1];
    const searchRange = {
      start: Math.max(0, errorLine - CODE_MATCHING_CONFIG.maxDistanceFromError),
      end: Math.min(document.lineCount - 1, errorLine + CODE_MATCHING_CONFIG.maxDistanceFromError)
    };

    let bestMatch: { line: number; similarity: number } | null = null;

    for (let lineNum = searchRange.start; lineNum <= searchRange.end; lineNum++) {
      const lineText = document.lineAt(lineNum).text;
      const trimmedLineText = lineText.trim();
      
      if (!trimmedLineText.includes(identifier)) continue;
      
      const similarity = this.calculateCodeSimilarity(trimmedLineText, suggestedCode);
      const distance = Math.abs(lineNum - errorLine);
      const score = similarity - (distance * 0.02);

      if (score >= CODE_MATCHING_CONFIG.minSimilarity && 
          (!bestMatch || score > bestMatch.similarity)) {
        bestMatch = { line: lineNum, similarity: score };
      }
    }

    if (bestMatch) {
      return this.createMatchedSuggestion(suggestion, bestMatch.line, document);
    }
    return null;
  }

  private createMatchedSuggestion(
    suggestion: ParsedFixSuggestion,
    lineNumber: number,
    document: vscode.TextDocument
  ): MatchedFixSuggestion {
    const lineText = document.lineAt(lineNumber).text;
    const originalIndentation = this.extractIndentation(lineText);
    const adjustedCode = this.adjustCodeIndentation(suggestion.suggestedCode, originalIndentation);

    return {
      originalCode: lineText.trim(),
      suggestedCode: suggestion.suggestedCode,
      line: lineNumber,
      originalIndentation,
      adjustedCode,
      lineIndex: suggestion.lineIndex
    };
  }

  private extractIndentation(lineText: string): string {
    const match = lineText.match(/^(\s*)/);
    return match ? match[1] : '';
  }

  private adjustCodeIndentation(suggestedCode: string, targetIndentation: string): string {
    const trimmedCode = suggestedCode.trim();
    if (trimmedCode.includes('\n')) {
      const lines = trimmedCode.split('\n');
      const adjustedLines = lines.map((line, index) => {
        if (index === 0) {
          return targetIndentation + line.trim();
        } else {
          const originalIndent = this.extractIndentation(line);
          const relativeIndent = originalIndent.length > 0 ? originalIndent : '    ';
          return targetIndentation + relativeIndent + line.trim();
        }
      });
      return adjustedLines.join('\n');
    } else {
      return targetIndentation + trimmedCode;
    }
  }

  private calculateCodeSimilarity(code1: string, code2: string): number {
    code1 = this.removeComments(code1);
    code2 = this.removeComments(code2);
    const normalize = (code: string) => {
      return code.toLowerCase().replace(/\s+/g, ' ').replace(/['"]/g, '"').trim();
    };

    const normalized1 = normalize(code1);
    const normalized2 = normalize(code2);
    
    if (normalized1 === normalized2) return 1.0;
    if (normalized1.includes(normalized2) || normalized2.includes(normalized1)) return 0.8;
    
    return this.calculateEditDistanceSimilarity(normalized1, normalized2);
  }

  private calculateEditDistanceSimilarity(str1: string, str2: string): number {
    const len1 = str1.length;
    const len2 = str2.length;
    const maxLen = Math.max(len1, len2);
    
    if (maxLen === 0) return 1.0;
    
    const matrix: number[][] = Array(len1 + 1).fill(null).map(() => Array(len2 + 1).fill(0));
    
    for (let i = 0; i <= len1; i++) matrix[i][0] = i;
    for (let j = 0; j <= len2; j++) matrix[0][j] = j;
    
    for (let i = 1; i <= len1; i++) {
      for (let j = 1; j <= len2; j++) {
        const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
        matrix[i][j] = Math.min(
          matrix[i - 1][j] + 1,
          matrix[i][j - 1] + 1,
          matrix[i - 1][j - 1] + cost
        );
      }
    }
    
    const editDistance = matrix[len1][len2];
    return 1 - (editDistance / maxLen);
  }

  /**
   * 方案1：使用模态对话框 + 快速操作
   */
  private async showFixSuggestionsModal(
    fixes: MatchedFixSuggestion[], 
    diagnostic: vscode.Diagnostic, 
    document: vscode.TextDocument,
    analysisResult: LLMAnalysisResult
  ): Promise<void> {
    console.log(`显示 ${fixes.length} 个修复建议（模态框模式）`);

    // 创建装饰器高亮相关代码行
    await this.highlightFixableLines(fixes, document);

    // 显示快速选择菜单
    const items: vscode.QuickPickItem[] = [
      {
        label: '🚀 应用所有修复',
        description: `一次性应用 ${fixes.length} 个修复建议`,
        detail: '推荐：批量修复所有问题'
      },
      ...fixes.map((fix, index) => ({
        label: `🔧 修复 ${index + 1}: 第${fix.line + 1}行`,
        description: fix.suggestedCode.substring(0, 50) + (fix.suggestedCode.length > 50 ? '...' : ''),
        detail: `原代码: ${fix.originalCode.substring(0, 40)}...`
      })),
      {
        label: '📋 查看详细分析',
        description: '在侧边栏查看完整的修复建议和分析',
        detail: '打开详细视图'
      },
      {
        label: '❌ 忽略所有建议',
        description: '关闭修复建议',
        detail: '不进行任何修复'
      }
    ];

    const selected = await vscode.window.showQuickPick(items, {
      placeHolder: '选择要执行的操作',
      title: `🔧 代码修复建议 (${fixes.length}个)`
    });

    if (!selected) {
      this.clearHighlights(document);
      return;
    }

    if (selected.label === '🚀 应用所有修复') {
      await this.applyAllFixes(fixes, document);
      vscode.window.showInformationMessage(`✅ 已应用所有 ${fixes.length} 个修复建议`);
    } else if (selected.label === '📋 查看详细分析') {
      await this.showDetailedPanel(fixes, diagnostic, document, analysisResult);
    } else if (selected.label === '❌ 忽略所有建议') {
      this.clearHighlights(document);
      vscode.window.showInformationMessage('已忽略所有修复建议');
    } else {
      // 应用单个修复
      const fixIndex = parseInt(selected.label.match(/修复 (\d+):/)?.[1] || '0') - 1;
      if (fixIndex >= 0 && fixIndex < fixes.length) {
        await this.applySingleFix(fixes[fixIndex], document);
        vscode.window.showInformationMessage(`✅ 已应用修复建议 ${fixIndex + 1}`);
      }
    }

    this.clearHighlights(document);
  }

  /**
   * 方案2：改进的侧边面板 - 保持编辑器焦点
   */
  private async showDetailedPanel(
    fixes: MatchedFixSuggestion[], 
    diagnostic: vscode.Diagnostic, 
    document: vscode.TextDocument,
    analysisResult: LLMAnalysisResult
  ): Promise<void> {
    // 保存当前活动编辑器的引用和位置
    const activeEditor = vscode.window.activeTextEditor;
    const originalViewColumn = activeEditor?.viewColumn;
    const originalSelection = activeEditor?.selection;

    console.log('保存编辑器状态:', { 
      hasActiveEditor: !!activeEditor, 
      viewColumn: originalViewColumn,
      documentUri: activeEditor?.document.uri.toString()
    });

    // 如果已有面板，先关闭
    if (this.currentPanel) {
      this.currentPanel.dispose();
    }

    // 创建新面板，使用 preserveFocus 保持编辑器焦点
    this.currentPanel = vscode.window.createWebviewPanel(
      'codeFixSuggestions',
      '🔧 代码修复建议',
      { 
        viewColumn: vscode.ViewColumn.Beside, 
        preserveFocus: true  // 关键：不夺取焦点
      },
      {
        enableScripts: true,
        retainContextWhenHidden: true,
        localResourceRoots: []
      }
    );

    // 生成HTML内容
    this.currentPanel.webview.html = this.getFixSuggestionHTML(fixes, diagnostic, analysisResult, document);

    // 处理用户交互
    this.currentPanel.webview.onDidReceiveMessage(async (message) => {
      console.log('收到面板消息:', message);
      
      try {
        await this.handleFixSuggestionMessage(message, fixes, document, this.currentPanel!);
        
        // 操作完成后，强制返回编辑器焦点
        await this.restoreEditorFocus(document, originalViewColumn, originalSelection);
        
      } catch (error) {
        console.error('处理面板消息失败:', error);
        vscode.window.showErrorMessage('操作失败: ' + error);
      }
    });

    // 面板可见性变化时保持编辑器焦点
    this.currentPanel.onDidChangeViewState((e) => {
      if (e.webviewPanel.visible && e.webviewPanel.active) {
        console.log('面板变为活动状态，恢复编辑器焦点');
        // 延迟恢复焦点，避免与面板激活冲突
        setTimeout(() => {
          this.restoreEditorFocus(document, originalViewColumn, originalSelection);
        }, 50);
      }
    });

    // 面板关闭时清理
    this.currentPanel.onDidDispose(() => {
      console.log('面板关闭，清理资源');
      this.clearHighlights(document);
      this.currentPanel = null;
    });

    // 存储活动修复建议
    const documentKey = document.uri.toString();
    this.activeFixes.set(documentKey, fixes);

    // 确保编辑器保持焦点 - 多重保障
    this.ensureEditorFocus(document, originalViewColumn, originalSelection);
  }

  /**
   * 确保编辑器保持焦点的多重保障机制
   */
  private async ensureEditorFocus(
    document: vscode.TextDocument, 
    viewColumn?: vscode.ViewColumn,
    selection?: vscode.Selection
  ): Promise<void> {
    const attempts = [50, 150, 300]; // 多次尝试，确保成功
    
    for (const delay of attempts) {
      setTimeout(async () => {
        try {
          await this.restoreEditorFocus(document, viewColumn, selection);
        } catch (error) {
          console.warn(`第${delay}ms尝试恢复焦点失败:`, error);
        }
      }, delay);
    }
  }

  /**
   * 恢复编辑器焦点
   */
  private async restoreEditorFocus(
    document: vscode.TextDocument,
    viewColumn?: vscode.ViewColumn,
    selection?: vscode.Selection
  ): Promise<void> {
    try {
      console.log('尝试恢复编辑器焦点...');
      
      // 方法1: 使用showTextDocument强制显示并聚焦
      const editor = await vscode.window.showTextDocument(document, {
        viewColumn: viewColumn || vscode.ViewColumn.One,
        preserveFocus: false, // 强制获取焦点
        preview: false
      });

      // 恢复原始选择位置
      if (selection && editor) {
        editor.selection = selection;
        editor.revealRange(selection, vscode.TextEditorRevealType.InCenterIfOutsideViewport);
      }

      console.log('编辑器焦点恢复成功');
      
    } catch (error) {
      console.error('恢复编辑器焦点失败:', error);
      
      // 备用方法: 直接查找匹配的编辑器
      const editors = vscode.window.visibleTextEditors;
      const targetEditor = editors.find(e => e.document.uri.toString() === document.uri.toString());
      
      if (targetEditor) {
        console.log('使用备用方法恢复焦点');
        await vscode.window.showTextDocument(targetEditor.document, targetEditor.viewColumn);
      }
    }
  }

  /**
   * 高亮可修复的代码行
   */
  private async highlightFixableLines(fixes: MatchedFixSuggestion[], document: vscode.TextDocument): Promise<void> {
    const editor = vscode.window.activeTextEditor;
    if (!editor || editor.document !== document) return;

    const decorationType = vscode.window.createTextEditorDecorationType({
      backgroundColor: new vscode.ThemeColor('editor.wordHighlightStrongBackground'),
      border: '1px solid',
      borderColor: new vscode.ThemeColor('editorWarning.foreground'),
      borderRadius: '3px',
      overviewRulerColor: new vscode.ThemeColor('editorWarning.foreground'),
      overviewRulerLane: vscode.OverviewRulerLane.Right
    });

    const decorations: vscode.DecorationOptions[] = fixes.map(fix => ({
      range: new vscode.Range(fix.line, 0, fix.line, document.lineAt(fix.line).text.length),
      hoverMessage: `🔧 修复建议 (来自suggestions第${fix.lineIndex + 1}行)\n原代码: ${fix.originalCode}\n建议代码: ${fix.adjustedCode}`
    }));

    editor.setDecorations(decorationType, decorations);
    
    const documentKey = document.uri.toString();
    this.fixDecorations.set(documentKey, decorationType);
  }

  /**
   * 清除高亮
   */
  private clearHighlights(document: vscode.TextDocument): void {
    const documentKey = document.uri.toString();
    const decorationType = this.fixDecorations.get(documentKey);
    
    if (decorationType) {
      const editor = vscode.window.activeTextEditor;
      if (editor) {
        editor.setDecorations(decorationType, []);
      }
      decorationType.dispose();
      this.fixDecorations.delete(documentKey);
    }
  }

  /**
   * 生成修复建议HTML - 添加快捷键支持
   */
  private getFixSuggestionHTML(
    fixes: MatchedFixSuggestion[], 
    diagnostic: vscode.Diagnostic, 
    analysisResult: LLMAnalysisResult,
    document: vscode.TextDocument
  ): string {
    const errorLine = diagnostic.range.start.line + 1;
    
    return `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>代码修复建议</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background-color: var(--vscode-editor-background);
            color: var(--vscode-editor-foreground);
        }
        .header {
            border-bottom: 2px solid var(--vscode-editorWarning-foreground);
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        .quick-actions {
            background-color: var(--vscode-editor-inactiveSelectionBackground);
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 6px;
            border-left: 4px solid var(--vscode-button-background);
        }
        .quick-btn {
            display: inline-block;
            padding: 8px 16px;
            margin: 5px 10px 5px 0;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.2s;
            text-decoration: none;
        }
        .quick-btn-primary {
            background-color: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
        }
        .quick-btn-primary:hover {
            background-color: var(--vscode-button-hoverBackground);
        }
        .quick-btn-secondary {
            background-color: var(--vscode-button-secondaryBackground);
            color: var(--vscode-button-secondaryForeground);
        }
        .error-info {
            background-color: var(--vscode-inputValidation-errorBackground);
            border-left: 4px solid var(--vscode-inputValidation-errorBorder);
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        .analysis-section {
            background-color: var(--vscode-editor-inactiveSelectionBackground);
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 6px;
            border-left: 4px solid var(--vscode-editorInfo-foreground);
        }
        .fix-item {
            background-color: var(--vscode-input-background);
            border: 1px solid var(--vscode-input-border);
            border-radius: 6px;
            margin-bottom: 15px;
            overflow: hidden;
        }
        .fix-header {
            background-color: var(--vscode-editorWidget-background);
            padding: 12px 15px;
            border-bottom: 1px solid var(--vscode-input-border);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .fix-content {
            padding: 15px;
        }
        .code-block {
            background-color: var(--vscode-textCodeBlock-background);
            border: 1px solid var(--vscode-textSeparator-foreground);
            border-radius: 4px;
            padding: 12px;
            margin: 10px 0;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 13px;
            overflow-x: auto;
            white-space: pre;
        }
        .original-code { border-left: 4px solid var(--vscode-editorError-foreground); }
        .suggested-code { border-left: 4px solid var(--vscode-editorInfo-foreground); }
        .adjusted-code { border-left: 4px solid var(--vscode-terminal-ansiGreen); }
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.2s;
        }
        .btn-primary {
            background-color: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
        }
        .btn-primary:hover {
            background-color: var(--vscode-button-hoverBackground);
        }
        .line-indicator {
            display: inline-block;
            background-color: var(--vscode-badge-background);
            color: var(--vscode-badge-foreground);
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: bold;
        }
        .keyboard-hint {
            font-size: 11px;
            color: var(--vscode-descriptionForeground);
            margin-left: 10px;
        }
        h1, h2, h3 { margin-top: 0; }
    </style>
</head>
<body>
    <div class="header">
        <h1>🔧 智能代码修复建议</h1>
        <p>从后端suggestions字段解析出的修复建议（已处理缩进）</p>
    </div>

    <div class="quick-actions">
        <h3>⚡ 快速操作</h3>
        <button class="quick-btn quick-btn-primary" onclick="applyAllFixes()">
            🚀 应用所有修复 <span class="keyboard-hint">(推荐)</span>
        </button>
        <button class="quick-btn quick-btn-secondary" onclick="dismissAll()">
            ❌ 忽略所有建议
        </button>
    </div>

    <div class="error-info">
        <h3>❌ 错误信息</h3>
        <p><strong>位置:</strong> 第 ${errorLine} 行</p>
        <p><strong>消息:</strong> ${diagnostic.message}</p>
    </div>

    <div class="analysis-section">
        <h3>🧠 智能分析</h3>
        <div style="white-space: pre-line;">${this.escapeHtml(analysisResult.analysis)}</div>
    </div>

    <div class="fixes-section">
        <h3>🛠️ 修复建议详情 (${fixes.length}个)</h3>
        ${fixes.map((fix, index) => `
            <div class="fix-item">
                <div class="fix-header">
                    <div>
                        <strong>修复 ${index + 1}</strong>
                        <span class="line-indicator">第 ${fix.line + 1} 行</span>
                    </div>
                    <button class="btn btn-primary" onclick="applyFix(${index})">🔄 应用此修复</button>
                </div>
                <div class="fix-content">
                    <div>🔴 原代码:</div>
                    <div class="code-block original-code">${this.escapeHtml(document.lineAt(fix.line).text)}</div>
                    
                    <div>🟢 修复后:</div>
                    <div class="code-block adjusted-code">${this.escapeHtml(fix.adjustedCode)}</div>
                </div>
            </div>
        `).join('')}
    </div>

    <script>
        const vscode = acquireVsCodeApi();

        // 添加键盘快捷键支持
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch(e.key) {
                    case 'Enter':
                        e.preventDefault();
                        applyAllFixes();
                        break;
                    case 'Escape':
                        e.preventDefault();
                        dismissAll();
                        break;
                }
            }
        });

        function applyFix(index) {
            vscode.postMessage({
                command: 'applyFix',
                fixIndex: index
            });
        }

        function applyAllFixes() {
            vscode.postMessage({
                command: 'applyAllFixes'
            });
        }

        function dismissAll() {
            vscode.postMessage({
                command: 'dismissAll'
            });
        }
    </script>
</body>
</html>`;
  }

  /**
   * 处理修复建议消息
   */
  private async handleFixSuggestionMessage(
    message: any, 
    fixes: MatchedFixSuggestion[], 
    document: vscode.TextDocument, 
    panel: vscode.WebviewPanel
  ): Promise<void> {
    try {
      switch (message.command) {
        case 'applyFix':
          await this.applySingleFix(fixes[message.fixIndex], document);
          vscode.window.showInformationMessage(`✅ 已应用第 ${message.fixIndex + 1} 个修复建议`);
          break;

        case 'applyAllFixes':
          await this.applyAllFixes(fixes, document);
          vscode.window.showInformationMessage(`✅ 已应用所有 ${fixes.length} 个修复建议`);
          panel.dispose();
          break;

        case 'dismissAll':
          this.clearHighlights(document);
          panel.dispose();
          vscode.window.showInformationMessage('已忽略所有修复建议');
          break;
      }
    } catch (error) {
      console.error('处理修复建议消息失败:', error);
      vscode.window.showErrorMessage('执行修复操作失败');
    }
  }

  /**
   * 应用单个修复
   */
  private async applySingleFix(fix: MatchedFixSuggestion, document: vscode.TextDocument): Promise<void> {
    const editor = vscode.window.activeTextEditor;
    if (!editor || editor.document !== document) {
      throw new Error('当前编辑器与文档不匹配');
    }

    const line = fix.line;
    const lineRange = new vscode.Range(line, 0, line, document.lineAt(line).text.length);
    
    await editor.edit(editBuilder => {
      editBuilder.replace(lineRange, fix.adjustedCode);
    });

    editor.selection = new vscode.Selection(line, fix.originalIndentation.length, line, fix.originalIndentation.length);
    editor.revealRange(new vscode.Range(line, 0, line, 0));
  }

  /**
   * 应用所有修复
   */
  private async applyAllFixes(fixes: MatchedFixSuggestion[], document: vscode.TextDocument): Promise<void> {
    const editor = vscode.window.activeTextEditor;
    if (!editor || editor.document !== document) {
      throw new Error('当前编辑器与文档不匹配');
    }

    const sortedFixes = [...fixes].sort((a, b) => b.line - a.line);

    await editor.edit(editBuilder => {
      for (const fix of sortedFixes) {
        const line = fix.line;
        const lineRange = new vscode.Range(line, 0, line, document.lineAt(line).text.length);
        editBuilder.replace(lineRange, fix.adjustedCode);
      }
    });

    this.clearHighlights(document);
  }

  /**
   * 显示匹配失败的模态提示
   */
  private async showFailedMatchModal(analysisResult: LLMAnalysisResult): Promise<void> {
    const choice = await vscode.window.showWarningMessage(
      '🔍 无法自动定位修复位置，但已生成分析建议',
      { modal: false },
      '查看分析结果',
      '忽略'
    );

    if (choice === '查看分析结果') {
      this.showAnalysisOnlyModal(analysisResult);
    }
  }

  /**
   * 显示仅包含分析结果的模态框
   */
  private async showAnalysisOnlyModal(analysisResult: LLMAnalysisResult): Promise<void> {
    const analysisText = `${analysisResult.analysis}\n\n修复建议:\n${analysisResult.suggestions}`;
    
    await vscode.window.showInformationMessage(
      analysisText.length > 200 ? analysisText.substring(0, 200) + '...' : analysisText,
      { modal: true },
      '确定'
    );
  }

  private escapeHtml(text: string): string {
    return text
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  /**
   * 清理资源
   */
  dispose(): void {
    for (const [, decorationType] of this.fixDecorations) {
      decorationType.dispose();
    }
    this.fixDecorations.clear();
    this.activeFixes.clear();
    
    if (this.currentPanel) {
      this.currentPanel.dispose();
      this.currentPanel = null;
    }
  }
}

// 导出管理器实例
export const codeFixManager = new CodeFixSuggestionManager();

/**
 * 处理后端LSP分析结果（主入口函数）
 */
export async function handleLSPAnalysisResult(
  analysisResult: LLMAnalysisResult,
  diagnostic: vscode.Diagnostic,
  document: vscode.TextDocument
): Promise<void> {
  await codeFixManager.processLSPAnalysisResult(analysisResult, diagnostic, document);
}

/**
 * 清理所有修复建议
 */
export function clearAllFixSuggestions(): void {
  codeFixManager.dispose();
}